<?php

class QQTranslator {

    // =========================================================================
    // 成员变量
    // =========================================================================

    private $secretId = "";
    private $secretKey = "";
    private $porjectId = 0;
    private $sourceLanguage = "auto";
    private $targetLanguage = "zh";
    private $region = "ap-hongkong";


    // =========================================================================
    // 公共成员函数
    // =========================================================================

    /**
     * 设置 secret Id
     * @param $id
     */
    public function setSecretId($id) {
        $this->secretId = $id;
    }

    /**
     * 设置 secret key
     * @param $key
     */
    public function setSecretKey($key) {
        $this->secretKey = $key;
    }

    /**
     * 设置 project id
     * @param $id
     */
    public function setProjectId($id) {
        $this->porjectId = $id;
    }

    /**
     * 指定源语言
     * @param $str
     */
    public function setSourceLanguage($str) {
        $this->sourceLanguage = $str;
    }

    /**
     * 指定目标语言
     * @param $str
     */
    public function setTargetLanguage($str) {
        $this->targetLanguage = $str;
    }

    /**
     * 设置 the 所在地域 of 服务器 that 响应用户请求
     * @param $str
     */
    public function setRegion($str) {
        $this->region = $str;
    }

    // -------------------------------------------------------------------------

    /**
     * 一次翻译一个句子
     * @param $sourceText string 待翻译的内容
     * @param $sourceLanguage string 可选。默认值为 auto，自动识别源语言
     * @param $targetLanguage string 可先。默认值为 zh，指定目标语言为简体中文
     * @return string 请求成功，返回翻译后的内容；请求失败，返回错误提示。
     */
    public function translateString($sourceText) {

        $secretId = $this->secretId;
        $secretKey = $this->secretKey;
        $projectId = $this->porjectId;
        $region = $this->region;
        $sourceLanguage = "";
        $targetLanguage = "";

        // 取得 a 数组 of 传入的参数
        $arr = func_get_args();
        $count = count($arr);

        switch ($count) {
            case 1:
                // 用户未指定源语言和目标语言
                $sourceLanguage = $this->sourceLanguage;
                $targetLanguage = $this->targetLanguage;
                break;
            case 2:
                // 用户未指定目标语言
                $sourceLanguage = $this->sourceLanguage;
                $targetLanguage = $arr[1];
                break;
            case 3:
                // 用户同时指定了源语言和目标语言
                $sourceLanguage = $arr[1];
                $targetLanguage = $arr[2];
        }

        $params = array(
            'Action'     => 'TextTranslate',
            'Region'     => $region,
            'ProjectId'  => $projectId,
            'SecretId'   => $secretId,
            'Source'     => $sourceLanguage,
            'Target'     => $targetLanguage,
            'SourceText' => $sourceText,
            'Timestamp'  => strval(time()),
            'Nonce'      => strval(rand()),
            'Version'    => '2018-03-21',
            'Signature'  => '',
        );

        $params['Signature'] = $this->getReqSign($params, $secretKey);
        $url = 'https://tmt.tencentcloudapi.com/';
        $response = $this->doHttpPost($url, $params);
        $responseArray = json_decode($response, true);

        if (isset($responseArray['Response']['TargetText'])) {
            $targetText = $responseArray["Response"]['TargetText'];
            return $targetText;
        } elseif (isset($responseArray['Response']['Error'])) {
            $errorCode = $responseArray['Response']['Error']['Code'];
            $errorMessage = $responseArray['Response']['Error']['Message'];
            return "获取翻译失败。错误代码：" . $errorCode . "，错误描述：" . $errorMessage;
        } else {
            return "获取翻译失败。未知错误。";
        }

    }

    // -------------------------------------------------------------------------

    /**
     * 一次翻译多个句子
     * @param $sourceTextList Array 一个数组，包含多个待翻译的句子
     * @return mixed|string 翻译成功返回一个数组，翻译失败返回一个字符串
     */
    public function translateStrings($sourceTextList)
    {

        $secretId = $this->secretId;
        $secretKey = $this->secretKey;
        $projectId = $this->porjectId;
        $region = $this->region;
        $sourceLanguage = "";
        $targetLanguage = "";

        // 取得 a 数组 of 传入的参数
        $arr = func_get_args();
        $count = count($arr);

        switch ($count) {
            case 1:
                $sourceLanguage = $this->sourceLanguage;
                $targetLanguage = $this->targetLanguage;
                break;
            case 2:
                $sourceLanguage = $this->sourceLanguage;
                $targetLanguage = $arr[1];
                break;
            case 3:
                $sourceLanguage = $arr[1];
                $targetLanguage = $arr[2];
        }

        $params = array(
            'Action' => 'TextTranslateBatch',
            'Region' => $region,
            'ProjectId' => $projectId,
            'SecretId' => $secretId,
            'Source' => $sourceLanguage,
            'Target' => $targetLanguage,
            'Timestamp' => strval(time()),
            'Nonce' => strval(rand()),
            'Version' => '2018-03-21',
            'Signature' => '',
        );

        $counter = 0;

        foreach ($sourceTextList as $sourceText) {
            $itemName = 'SourceTextList.' . $counter;
            $params[$itemName] = $sourceText;
            $counter += 1;
        }

        $params['Signature'] = $this->getReqSign($params, $secretKey);

        $url = 'https://tmt.tencentcloudapi.com/';
        $response = $this->doHttpPost($url, $params);
        $responseArray = json_decode($response, true);

        if (isset($responseArray['Response']['TargetTextList'])) {
            return $responseArray['Response']['TargetTextList'];
        } elseif (isset($responseArray['Response']['Error'])) {
            $errorCode = $responseArray['Response']['Error']['Code'];
            $errorMessage = $responseArray['Response']['Error']['Message'];
            return "获取翻译失败。错误代码：" . $errorCode . "，错误描述：" . $errorMessage;
        } else {
            return "获取翻译失败。未知错误。";
        }

    }


    // =========================================================================
    // 私有成员函数
    // =========================================================================

    // getReqSign ：根据 接口请求参数 和 应用密钥 计算 请求签名
    // 参数说明
    //   - $params：接口请求参数（特别注意：不同的接口，参数对一般不一样，请以具体接口要求为准）
    //   - $appkey：应用密钥
    // 返回数据
    //   - 签名结果
    private function getReqSign($params, $appkey)
    {
        // 1. 对参数排序
        ksort($params);

        // 2. 拼接请求字符串
        // 参数值为原始值而非编码后的值

        $str = '';
        $counter = 1;
        foreach ($params as $key => $value)
        {
            if ($value !== '')
            {
                if ($counter == 1) {
                    $str .= $key . '=' . $value;
                    $counter += 1;
                } else {
                    $str .= '&' . $key . '=' . $value;
                }
            }
        }

        // 3. 拼接签名原文字符串
        // 签名原文串的拼接规则为：请求方法 + 请求主机 +请求路径 + ? + 请求字符串。
        $str = 'POST' . 'tmt.tencentcloudapi.com' . '/' . '?' . $str;

        // 4. 生成签名串
        $sign = base64_encode(hash_hmac('sha1', $str, $appkey, true));

        return $sign;

    }

    // doHttpPost ：执行POST请求，并取回响应结果
    // 参数说明
    //   - $url   ：接口请求地址
    //   - $params：完整接口请求参数（特别注意：不同的接口，参数对一般不一样，请以具体接口要求为准）
    // 返回数据
    //   - 返回false表示失败，否则表示API成功返回的HTTP BODY部分
    private function doHttpPost($url, $params)
    {
        $curl = curl_init();

        $response = false;
        do
        {
            // 1. 设置HTTP URL (API地址)
            curl_setopt($curl, CURLOPT_URL, $url);

            // 2. 设置HTTP HEADER (表单POST)
            $head = array(
                'Content-Type: application/x-www-form-urlencoded'
            );
            curl_setopt($curl, CURLOPT_HTTPHEADER, $head);

            // 3. 设置HTTP BODY (URL键值对)
            $body = http_build_query($params);
            curl_setopt($curl, CURLOPT_POST, true);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $body);

            // 4. 调用API，获取响应结果
            curl_setopt($curl, CURLOPT_HEADER, false);
            curl_setopt($curl, CURLOPT_NOBODY, false);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            $response = curl_exec($curl);
            if ($response === false)
            {
                $response = false;
                break;
            }

            $code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
            if ($code != 200)
            {
                $response = false;
                break;
            }
        } while (0);

        curl_close($curl);
        return $response;
    }

    // -------------------------------------------------------------------------

}
